package com.css.zfzx.sjcj.modules.hddcRock25Pre.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcRock25Pre.repository.HddcRock25preNativeRepository;
import com.css.zfzx.sjcj.modules.hddcRock25Pre.repository.HddcRock25preRepository;
import com.css.zfzx.sjcj.modules.hddcRock25Pre.repository.entity.HddcRock25preEntity;
import com.css.zfzx.sjcj.modules.hddcRock25Pre.service.HddcRock25preService;
import com.css.zfzx.sjcj.modules.hddcRock25Pre.viewobjects.HddcRock25preQueryParams;
import com.css.zfzx.sjcj.modules.hddcRock25Pre.viewobjects.HddcRock25preVO;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import org.springframework.data.domain.PageImpl;
import com.css.bpm.platform.utils.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author zyb
 * @date 2020-11-27
 */
@Service
public class HddcRock25preServiceImpl implements HddcRock25preService {

	@Autowired
    private HddcRock25preRepository hddcRock25preRepository;
    @Autowired
    private HddcRock25preNativeRepository hddcRock25preNativeRepository;

    @Override
    public JSONObject queryHddcRock25pres(HddcRock25preQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcRock25preEntity> hddcRock25prePage = this.hddcRock25preNativeRepository.queryHddcRock25pres(queryParams, curPage, pageSize, sort, order);
        List<HddcRock25preVO> hddcRock25preVOList = new ArrayList<>();
        List<HddcRock25preEntity> hddcRock25preEntityList = hddcRock25prePage.getContent();
        for(HddcRock25preEntity hddcRock25preEntity : hddcRock25preEntityList){
            HddcRock25preVO hddcRock25preVO = new HddcRock25preVO();
            BeanUtils.copyProperties(hddcRock25preEntity, hddcRock25preVO);
            if(PlatformObjectUtils.isNotEmpty(hddcRock25preEntity.getSymbol())) {
                String dictItemCode=String.valueOf(hddcRock25preEntity.getSymbol());
                hddcRock25preVO.setSymbolName(findByDictCodeAndDictItemCode("RockTypeCVD", dictItemCode));
            }
            hddcRock25preVOList.add(hddcRock25preVO);
        }
        Page<HddcRock25preVO> HddcRock25preVOPage = new PageImpl(hddcRock25preVOList, hddcRock25prePage.getPageable(), hddcRock25prePage.getTotalElements());
        JSONObject jsonObject = PlatformPageUtils.formatPageData(HddcRock25preVOPage);
        return jsonObject;
    }


    @Override
    public HddcRock25preEntity getHddcRock25pre(String id) {
        HddcRock25preEntity hddcRock25pre = this.hddcRock25preRepository.findById(id).orElse(null);
         return hddcRock25pre;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcRock25preEntity saveHddcRock25pre(HddcRock25preEntity hddcRock25pre) {
        String uuid = UUIDGenerator.getUUID();
        hddcRock25pre.setUuid(uuid);
        hddcRock25pre.setCreateUser(PlatformSessionUtils.getUserId());
        hddcRock25pre.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcRock25pre.setIsValid("1");
        this.hddcRock25preRepository.save(hddcRock25pre);
        return hddcRock25pre;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcRock25preEntity updateHddcRock25pre(HddcRock25preEntity hddcRock25pre) {
        UpdateUtil.copyNullProperties(hddcRock25preRepository.findByUuidAndIsValid(hddcRock25pre.getUuid(), "1"),hddcRock25pre);
        hddcRock25pre.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcRock25pre.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcRock25preRepository.save(hddcRock25pre);
        return hddcRock25pre;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcRock25pres(List<String> ids) {
        List<HddcRock25preEntity> hddcRock25preList = this.hddcRock25preRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcRock25preList) && hddcRock25preList.size() > 0) {
            for(HddcRock25preEntity hddcRock25pre : hddcRock25preList) {
                hddcRock25pre.setIsValid("0");
                hddcRock25pre.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcRock25pre.setUpdateTime(new Date());
                this.hddcRock25preRepository.save(hddcRock25pre);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public String findByDictCodeAndDictItemCode(String dictCode, String dictItemCode){
        DictItemEntity dictItem = PlatformAPI.getDictAPI().getValidDictItemByDictCodeAndDictItemCode(dictCode, dictItemCode);
        String dictItemName = "";
        if(PlatformObjectUtils.isNotEmpty(dictItem)){
            dictItemName = dictItem.getDictItemName();
        }
        return dictItemName;
    }

    @Override
    public void exportFile(HddcRock25preQueryParams queryParams, HttpServletResponse response) {
        List<HddcRock25preEntity> yhDisasterEntities = hddcRock25preNativeRepository.exportYhDisasters(queryParams);
        List<HddcRock25preVO> list=new ArrayList<>();
        for (HddcRock25preEntity entity:yhDisasterEntities) {
            HddcRock25preVO yhDisasterVO=new HddcRock25preVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "1：25万工作底图岩体-面", "1：25万工作底图岩体-面", HddcRock25preVO.class, "1：25万工作底图岩体-面.xls", response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcRock25preVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcRock25preVO.class, params);
            List<HddcRock25preVO> list = result.getList();
            // Excel条数据
            int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcRock25preVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcRock25preVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }
    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList( List<HddcRock25preVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcRock25preEntity yhDisasterEntity = new HddcRock25preEntity();
            HddcRock25preVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcRock25pre(yhDisasterEntity);
        }
    }

}
